package com.water.note.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.water.note.entity.Todo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 待办事项Mapper接口
 */
@Mapper
public interface TodoMapper extends BaseMapper<Todo> {
    
    /**
     * 分页查询待办事项
     *
     * @param page 分页参数
     * @param userId 用户ID
     * @param status 状态
     * @param keyword 关键字
     * @return 待办事项列表
     */
    @Select("<script>" +
            "SELECT * FROM t_todo " +
            "WHERE deleted = 0 AND user_id = #{userId} " +
            "<if test='status != null'> AND status = #{status} </if>" +
            "<if test='keyword != null and keyword != \"\"'> AND (title LIKE CONCAT('%', #{keyword}, '%') OR content LIKE CONCAT('%', #{keyword}, '%')) </if>" +
            "ORDER BY priority DESC, deadline ASC, create_time DESC" +
            "</script>")
    IPage<Todo> pageTodos(Page<Todo> page, @Param("userId") Long userId, @Param("status") Integer status, @Param("keyword") String keyword);
    
    /**
     * 查询今日待办事项
     *
     * @param userId 用户ID
     * @return 待办事项列表
     */
    @Select("SELECT * FROM t_todo " +
            "WHERE deleted = 0 AND user_id = #{userId} " +
            "AND status IN (0, 1) " +
            "AND DATE(deadline) = CURDATE() " +
            "ORDER BY priority DESC, deadline ASC")
    List<Todo> listTodayTodos(@Param("userId") Long userId);
    
    /**
     * 查询未完成且已过期的待办事项
     *
     * @param userId 用户ID
     * @return 待办事项列表
     */
    @Select("SELECT * FROM t_todo " +
            "WHERE deleted = 0 AND user_id = #{userId} " +
            "AND status IN (0, 1) " +
            "AND deadline < NOW() " +
            "ORDER BY priority DESC, deadline ASC")
    List<Todo> listOverdueTodos(@Param("userId") Long userId);
    
    /**
     * 更新待办事项状态
     *
     * @param todoId 待办事项ID
     * @param status 状态
     * @return 影响行数
     */
    @Update("UPDATE t_todo SET status = #{status} " +
            "<if test='status == 2'>, complete_time = NOW() </if>" +
            "WHERE id = #{todoId}")
    int updateTodoStatus(@Param("todoId") Long todoId, @Param("status") Integer status);
    
    /**
     * 更新提醒状态
     *
     * @param todoId 待办事项ID
     * @param isReminded 是否已提醒
     * @return 影响行数
     */
    @Update("UPDATE t_todo SET is_reminded = #{isReminded} WHERE id = #{todoId}")
    int updateRemindStatus(@Param("todoId") Long todoId, @Param("isReminded") Integer isReminded);
} 